package guyubao.com.controller;

import guyubao.com.entity.RestBean;
import guyubao.com.service.LoginMapperUserService;
import guyubao.com.service.RedisService;
import guyubao.com.utils.Const;
import io.swagger.v3.oas.annotations.Operation;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.function.Function;
import java.util.function.Supplier;


/**
 * 基础控制器
 * @author wxa
 */
@Slf4j
public class BaseController {
    @Resource
    RedisService redisService;
    
    @Operation(summary = "针对于返回值为String作为错误信息的方法进行统一处理")
    protected RestBean<Void> messageHandle(Supplier<String> action) {
        String message = action.get();
        return message == null ? RestBean.success() : RestBean.failure(400, message);
    }
    
    @Operation(summary = "对类型进行方法引用")
    protected <T> RestBean<Void> messageHandle(T vo, Function<T, String> function) {
        return messageHandle(() -> function.apply(vo));
    }
    
    @Resource
    LoginMapperUserService loginMapperUserService;
    
    // 验证该账号是否属于用户
    protected String verification(String uid, String id) {
        String idByUId = loginMapperUserService.getIdByUId(uid);
        if (idByUId == null || !id.equals(idByUId)) {
            return "没有该账号,或者该账号不属于此用户！";
        }
        return null;
    }
    
    // 验证该账号是否属于用户并且验证验证码
    protected String verification(String uid, String id, String emailType, String email, String code) {
        // 验证该账号是否属于用户
        String rs = verification(uid, id);
        if (rs != null) {
            return rs;
        }
        // 验证验证码
        String redisCode = redisService.getEmailVerifyCode(emailType, email);
        if (redisCode == null) {
            return "请获取验证码进行验证！";
        }
        if (!redisCode.equals(code)) {
            redisService.deleteEmailVerifyCode(emailType, email);
            return "验证码错误,请重新获取验证码进行验证！";
        }
        redisService.deleteEmailVerifyCode(emailType, email);
        return null;
    }
    
    protected Boolean isAdmin(String role) {
        if (!role.equals(Const.ATTR_ROLE_ADMIN)) {
            log.warn("危险呀，有人摸到了管理员接口啊");
            return false;
        }
        return true;
    }
}
